# import socket  #导入socket模块
# import tkinter as tk

# s=socket.socket()  #创建socket对象
# host=socket.gethostname()  #获取本地主机名
# port=12345  #设置端口号
# s.bind((host,port))  #绑定端口
# s.listen(5)  #等待客户端连接，参数表示等待连接的最大数量
# while True:
#     c,addr=s.accept()  #建立客户端连接
#     print('连接地址',addr)  #打印客户端地址
#     msg=input('请输入信息：')   
#     c.send(msg.encode('utf-8'))  #发送信息
#     c.close()  #关闭连接


# import socket
# import tkinter as tk
# from threading import Thread

# # 创建窗口
# root = tk.Tk()
# root.title("Socket 服务端")
# root.geometry("400x300")

# # 输入框
# tk.Label(root, text="发送消息：").pack(pady=10)
# entry = tk.Entry(root, width=30)
# entry.pack()

# # 全局变量保存客户端连接
# client_conn = None

# # 接收客户端连接的函数（运行在子线程）
# def accept_client():
#     global client_conn
#     s = socket.socket()
#     s.bind((socket.gethostname(), 12345))
#     s.listen(5)
#     print("等待连接...")
#     while True:
#         client_conn, addr = s.accept()
#         print(f"已连接: {addr}")

# # 发送消息
# def send_msg():
#     msg = entry.get()
#     if msg and client_conn:
#         client_conn.send(msg.encode('utf-8'))

# # 启动监听线程
# Thread(target=accept_client, daemon=True).start()

# # 发送按钮
# tk.Button(root, text="发送", command=send_msg).pack(pady=20)

# # 运行界面
# root.mainloop()


import socket
import tkinter as tk
from threading import Thread

# 创建窗口
root = tk.Tk()
root.title("Socket 服务端")
root.geometry("400x300")

# 输入框
tk.Label(root, text="主机名：").grid(row=0, column=0, padx=10, pady=10)
hostname_entry = tk.Entry(root, width=30)
hostname_entry.grid(row=0, column=1, padx=10, pady=10)
hostname_entry.insert(0, "localhost")

tk.Label(root, text="端口号：").grid(row=1, column=0, padx=10, pady=10)
port_entry = tk.Entry(root, width=30)
port_entry.grid(row=1, column=1, padx=10, pady=10)
port_entry.insert(0, "12345")

# 全局变量保存客户端连接和服务器状态
client_conn = None
server_socket = None
is_running = False

# 接收客户端连接的函数（运行在子线程）
def accept_client():
    global client_conn, server_socket, is_running
    hostname = hostname_entry.get()
    port = int(port_entry.get())
    
    if not hostname or not port:
        status_label.config(text="请输入有效的主机名和端口号！")
        return
    
    try:
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_socket.bind((hostname, port))
        server_socket.listen(5)
        print("等待连接...")
        while is_running:
            client_conn, addr = server_socket.accept()
            status_label.config(text=f"服务运行中！客户端 ('{addr[0]}', {addr[1]}) 已连接")
            print(f"已连接: {addr}")
    except Exception as e:
        status_label.config(text=f"错误：{str(e)}")
    finally:
        if server_socket:
            server_socket.close()

# 启动服务
def start_service():
    global is_running
    if not is_running:
        is_running = True
        Thread(target=accept_client, daemon=True).start()
        status_label.config(text="服务已启动，等待连接...")

# 停止服务
def stop_service():
    global is_running, server_socket
    if is_running:
        is_running = False
        if server_socket:
            server_socket.close()
        status_label.config(text="服务已停止")

# 按钮
start_button = tk.Button(root, text="启动服务", command=start_service)
start_button.grid(row=2, column=0, padx=10, pady=20)

stop_button = tk.Button(root, text="停止服务", command=stop_service)
stop_button.grid(row=2, column=1, padx=10, pady=20)

# 状态标签
status_label = tk.Label(root, text="", fg="green")
status_label.grid(row=3, column=0, columnspan=2, padx=10, pady=10)

# 运行界面
root.mainloop()